package javax.core.security.service;

import org.springframework.beans.factory.annotation.Autowired;

import javax.core.security.AuthenticationManager;
import javax.core.security.entity.credential.AuthCredential;
import javax.core.security.entity.UserAuthentication;
import javax.core.security.exception.AuthenticationException;
import javax.core.security.provider.AuthenticationProvider;
import java.util.List;

/**
 * @author wenlong
 * 只能适配使用 UserAuthenication 的鉴权, 如果是Spring应用需要通过 @Bean 来容器化
 */
public class DefaultAuthenticationManager implements AuthenticationManager {

    @Autowired
    List<AuthenticationProvider> authenticationProviderList;

    /**
     * 自定义通用登录/鉴权的方法
     * @param authCredential 只能是 {@link AuthCredential} 对象
     */
    @Override
    public UserAuthentication authenticate(AuthCredential authCredential) throws AuthenticationException {
        if (authenticationProviderList == null || authenticationProviderList.isEmpty()) {
            throw new AuthenticationException("There is no Authentication Provider Defined, make sure you configuration is correct," +
                    "check whether the AuthenticationProvider is injected.");
        }
        for (AuthenticationProvider provider : authenticationProviderList) {
            if (provider.supports(authCredential)) {
                UserAuthentication authResult = provider.authenticate(authCredential);
                if (authResult != null) {
                    return authResult;
                }
            }
        }
        throw new AuthenticationException("Account authentication failed, no suitable provider");
    }
}
